//
//  OrderViewController.swift
//  newShaohuoRen
//
//  Created by hujinbiao on 2018/3/23.
//  Copyright © 2018年 hujinbiao. All rights reserved.
//

import UIKit
import MJRefresh
import SwiftProgressHUD

let cellIdentifier = "AlittleCell"

class OrderViewController: UIViewController {
    
    var orderTableView : UITableView?
    
    var orderArray = NSMutableArray()
    
    var page = 0
    var totalPage = 0
    
    var type = "1"
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadTableView()
    
    }

    private func loadTableView() {
        
        orderTableView = UITableView(frame: self.view.bounds)
        orderTableView?.dataSource = self
        orderTableView?.delegate = self
        orderTableView?.tableFooterView = UIView()
        orderTableView?.register(UINib.init(nibName: "AlittleCell", bundle: nil), forCellReuseIdentifier: cellIdentifier)
        orderTableView?.rowHeight = UITableViewAutomaticDimension
        orderTableView?.estimatedRowHeight = 100
        self.view.addSubview(orderTableView!)
        
        refresh()
        orderTableView?.mj_header.beginRefreshing()
    }
    
    func refresh() {
        
        // 顶部刷新
        let header = MJRefreshNormalHeader()
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        orderTableView?.mj_header = header
        
        // 底部刷新
        let footer = MJRefreshAutoNormalFooter()
        footer.setRefreshingTarget(self, refreshingAction: #selector(footerRefresh))
        orderTableView?.mj_footer = footer
        
    }
    
    // 顶部刷新
    @objc fileprivate func headerRefresh(){
        page = 1
        requestOrderListNew(type: type, current_page: page)
    }
    // 底部刷新
    @objc fileprivate func footerRefresh(){
        if page<=totalPage{
            requestOrderListMore(type: type, current_page: page)
        }else {
            self.orderTableView?.mj_footer.endRefreshing()
        }
    }
    
    func requestOrderListNew(type:String,current_page:Int) -> Void {
        
        //要加密的数据
        let param = ["command":"doneList","uid":UserTicketModel.sharedInstance.uid ?? "","token":UserTicketModel.sharedInstance.token ?? "","app_name":"shr","type":type,"per_page":"10"] as [String : Any]
        
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            self.orderTableView?.mj_header.endRefreshing()
            
            let jsonString = network.getJSONStringFromDictionary(dictionary: resultDict["data"] as! NSDictionary)
            guard let jsonData = jsonString.data(using: String.Encoding.utf8) else {return}
            do {
                let objc: AlittleItem = try JSONDecoder().decode(AlittleItem.self, from: jsonData)
                let alittles : [AlittleOrderItem] = objc.data
                self.page = objc.current_page+1
                self.totalPage = objc.total
                self.orderArray.removeAllObjects()
                for ali in alittles {
                    self.orderArray.add(ali)
                }
                self.orderTableView?.reloadData()
                
            }catch {
                print(error)
            }
        })
    }
    
    func requestOrderListMore(type:String,current_page:Int) -> Void {
        
        //要加密的数据
        let param = ["command":"doneList","uid":UserTicketModel.sharedInstance.uid ?? "","token":UserTicketModel.sharedInstance.token ?? "","app_name":"shr","type":type,"per_page":"10"] as [String : Any]
        
        let network = NetworkTools.sharedInstance
        network.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Shipping"], successed: { (resultDict) in
            self.orderTableView?.mj_header.endRefreshing()
            
            let jsonString = network.getJSONStringFromDictionary(dictionary: resultDict["data"] as! NSDictionary)
            guard let jsonData = jsonString.data(using: String.Encoding.utf8) else {return}
            do {
                let objc: AlittleItem = try JSONDecoder().decode(AlittleItem.self, from: jsonData)
                let alittles : [AlittleOrderItem] = objc.data
                self.page = objc.current_page+1
                self.totalPage = objc.total
                for ali in alittles {
                    self.orderArray.add(ali)
                }
                self.orderTableView?.reloadData()
                
            }catch {
                print(error)
            }
        })
    }

}


extension OrderViewController : UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.orderArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! AlittleCell
        cell.selectionStyle = .none
        let aliOrderItem = self.orderArray[indexPath.row] as! AlittleOrderItem
        cell.alittleOrderItem = aliOrderItem
        
        return cell
        
    }
}

